package com.training.java.redbox;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.actions.DispatchAction;

import com.training.java.redbox.domain.Customer;
import com.training.java.redbox.domain.CustomerDAO;
import com.training.java.redbox.domain.CustomerDaoJdbcImpl;

public class LoginAction extends DispatchAction {
	
	public ActionForward redirect(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		return mapping.findForward("login");
	}
	
	
	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		UserForm userForm = (UserForm)form;
		
		CustomerDAO dao = new CustomerDaoJdbcImpl();
		
		Customer customer = dao.findByUsernameAndPassword(userForm.getUserName(), userForm.getPassword());
		
		if(customer!=null){			
			
			HttpSession session = request.getSession();
			session.setAttribute("customer", customer);		
			return mapping.findForward("list");

		
		}else{
			
			ActionErrors errors = new ActionErrors();			
			errors.add("invalidlogin", new ActionMessage("login.invalid"));
			
			saveErrors(request, errors);
			
			return mapping.findForward("login");
			
		}
		
		
	}

}
